/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * email:nur01@qq.com
 * @flow
 */

import React, {Component} from 'react';
import {
    ActivityIndicator,
    AsyncStorage,
    DeviceEventEmitter,
    Dimensions,
    FlatList,
    Image,
    LayoutAnimation,
    ListView,
    Platform,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    UIManager,
    View,
} from 'react-native';
import StyleUtils from "../res/styles/StyleUtils";
import GoodsRender from "../utils/GoodsRender";
import IparNetwork, {SERVER_TYPE} from "../httpUtils/IparNetwork";
import CommonUtils from "../common/CommonUtils";
import Carousel from 'react-native-banner-carousel';
import GoodsIsBuyPage from "./common/GoodsIsBuyPage";
import I18n from "../res/language/i18n";
import CategoryMinPage from "./category/CategoryMinPage";
import AdvertisementView from "../custom/AdvertisementView";
import IparImageView from "../custom/IparImageView";
import ViewUtils from "../utils/ViewUtils";
import VerifyPersonalPage from "./mePage/business/VerifyPersonalPage";
import BusinessPlanPage from "./mePage/business/BusinessPlanPage";

const width = Dimensions.get('window').width;

let ds = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 != row2,
});
export default class HomePage extends Component {
    // 构造
    constructor(props) {
        super(props);
        this.iparNetWork = new IparNetwork();
        // 初始状态

        this.commonUtils = new CommonUtils();


        this.countryIso = '';
        this.state = {
            loading: false,
            refreshing: false,
            visibleSwiper: false,
            onLoadEndImgTow: false,
            onLoadEndImgThree: false,
            showOperationView: false,
            isRefreshingUp: false,//上啦刷新
            refreshingUp: false,//可不可以上啦刷新
            isGoods: false,
            lang: I18n.locale,
            sliAdver: [],
            mid_adver: [],
            bottomAdver: [],
            newGoodsData: [],
            hotGoodsData: [],
            promoteGoodsData: [],
            globalGoodsData: [],
            suiteGoodsData: [],
            goodsData: [],
        };
    }


    /**
     * render 完成后
     */
    componentDidMount() {

        CommonUtils.getAcyncInfo('country_iso')
            .then((result) => {
                this.countryIso = result;
                this.onLOadData(result);//获取首页数据
            });


        setTimeout(() => {
            this.setState({
                visibleSwiper: true,
            });
        }, 100);
    }


    componentWillUnmount() {
        this.countryIso = null;
        this.commonUtils = null;
        this.upLoadData && this.upLoadData.remove();
    }


    /**
     * 获取首页数据
     * @param country 哪个国家（CN/ZH....）
     * @param isRankU_2 //是否U-2 program
     */
    onLOadData(country) {
        this.setState({
            refreshing: true,
        });


        let isRankU_2 = false;
        let userInfo = this.props.userInfo;
        if (userInfo && userInfo.rank === 6) {
            isRankU_2 = true;
        }

        let _market = isRankU_2 ? '&market=u2' : '';
        this.iparNetWork.getRequest(SERVER_TYPE.goods + 'home?', 'country=' + country + _market)
            .then((result) => {
                console.log(result);
                if (result.code === 200) {
                    let goodsData = result.data;
                    AsyncStorage.setItem('getPv', goodsData.pv ? JSON.stringify(goodsData.pv) : '', (error, result) => {
                        this.renderGoodsData(goodsData);
                    });

                } else {
                    this.setState({
                        refreshing: false,
                        showOperationView: true,
                    });
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))

                }
            })
            .catch((error) => {
                this.startAnimation();

                this.setState({
                    refreshing: false,
                    showOperationView: true,
                });
                console.log('homePage-error: ' + error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });
    }


    /**
     * 产品数据处理
     * @param goodsData
     */
    renderGoodsData(goodsData) {
        if (!goodsData) return;
        let goods = goodsData.goods;
        let _newGoodsData = [];
        let _hotGoodsData = [];
        let _promoteGoodsData = [];
        let _globalGoodsData = [];
        let _suiteGoodsData = [];
        for (let i = 0, len = goods.length; i < len; i++) {
            let goodsDatum = goods[i];

            var goodsItem = goodsDatum.goods || [];

            switch (goodsDatum.type) {
                case 'new':
                    _newGoodsData = goodsItem;
                    break;
                case 'hot':
                    _hotGoodsData = goodsItem;
                    break;
                case 'promote':
                    _promoteGoodsData = goodsItem;
                    break;
                case 'global':
                    _globalGoodsData = goodsItem;
                    break;
                case 'suite':
                    _suiteGoodsData = goodsItem;
                    break;
            }
        }


        this.startAnimation();
        this.setState({
            refreshing: false,
            showOperationView: true,
            isGoods: true,
            sliAdver: goodsData.sli_adver,
            mid_adver: goodsData.mid_adver || [],
            bottomAdver: goodsData.foot,
            newGoodsData: _newGoodsData,
            hotGoodsData: _hotGoodsData,
            promoteGoodsData: _promoteGoodsData,
            globalGoodsData: _globalGoodsData,
            suiteGoodsData: _suiteGoodsData,
            refreshingUp: true,
        });

    }

    /**
     * 每个列表的title view
     * */
    labelTitleRender(title, moreType, isCate) {


        return (
            <View
                style={[StyleUtils.justifySpace, StyleUtils.marginTop, {padding: 16,}]}>
                <Text
                    numberOfLines={1}
                    style={[StyleUtils.title, StyleUtils.smallFont, {flex: 1, textAlign: 'left'}]}>{title}</Text>
                <TouchableOpacity
                    onPress={() => {
                        if (isCate) {
                            this.props.navigator.push({
                                component: CategoryMinPage,
                                params: {
                                    title: title,
                                    cate_id: moreType,
                                    country: this.countryIso,
                                }
                            })
                        } else {
                            //如果用户点击global 的话跳第二个页面
                            if (moreType === 'global') {
                                DeviceEventEmitter.emit('goToPage', 1)
                            } else {
                                this.props.navigator.push({
                                    component: GoodsIsBuyPage,
                                    params: {
                                        goodsPage: moreType,
                                    }
                                })
                            }
                        }
                    }}
                    style={StyleUtils.justifySpace}>
                    <Text style={[styles.moreText, StyleUtils.smallFont]}
                    >{I18n.t('default.seeMore')}</Text>
                    <Image
                        style={[styles.moreIcon]}
                        source={require('../res/images/ic_right_more.png')}/>
                </TouchableOpacity>
            </View>
        )
    }


    /**
     * 获取list View
     * */
    getListView(dataSource) {


        return <ListView
            enableEmptySections={true}
            style={styles.listView}
            pageSize={1}
            dataSource={ds.cloneWithRows(dataSource)}
            automaticallyAdjustContentInsets={false}
            contentContainerStyle={styles.gridListStyle}
            renderRow={(rowData, sectionID, rowID) => this._renderRow(rowData, rowID)}/>
    }

    headresImageItems(item, i) {
        return <TouchableOpacity
            key={i}
            style={[styles.headerImages, StyleUtils.center]}
            onPress={() => this.commonUtils.onClickAdvers(item, this, this.countryIso)}>

            <IparImageView resizeMode={'cover'} errorImage={require('../res/images/ic_image_fail.png')} width={'100%'}
                           height={'100%'}
                           url={item.adver_img}/>

        </TouchableOpacity>
    }


    /**
     * category data
     */
    getHomeNewData() {
        if (!this.state.refreshingUp) {
            return;
        }
        this.setState({
            refreshingUp: false,
            isRefreshingUp: true,
        });
        this.iparNetWork.getRequest(SERVER_TYPE.goods + "homeCate?", 'country=' + this.countryIso)
            .then((result) => {
                this.setState({
                    isRefreshingUp: false,
                    refreshingUp: false,
                });
                if (result.code === 200) {
                    this.setState({
                        goodsData: result.data
                    });
                }
            })
            .catch((error) => {
                this.setState({
                    isRefreshingUp: false,
                    refreshingUp: false,
                });
                console.log('HomePage--getHomeNewData--error-' + error)
            });
    }

    /**
     * 动画效果
     */
    startAnimation() {
        if (Platform.OS === 'android') {
            UIManager.setLayoutAnimationEnabledExperimental(true);
        }
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    }

    render() {
        let headresImage = (this.state.visibleSwiper && this.state.sliAdver.length > 0 ?
            <View style={{height: (width / 2) + 20}}>
                <Carousel
                    autoplay={true}
                    autoplayTimeout={3000}
                    loop={true}
                    index={0}
                    showsPageIndicator={false}
                >
                    {this.state.sliAdver.map((item, index) => this.headresImageItems(item, index))}
                </Carousel>
            </View> : null);


        let userInfo = this.props.userInfo;
        let operationViewTitle = '';
        let operationViewUserData = null;
        let operationViewMsj = '';
        let operationViewType = null;
        if (userInfo) {
            if (userInfo.open_plan_num <= 1) {
                operationViewType = 1;
                operationViewTitle = I18n.t('b.notSubsribed');
                operationViewMsj = I18n.t('b.registerIsIBMMinContent');
            } else {
                operationViewTitle = null;
                operationViewMsj = null;
                operationViewUserData = userInfo;
            }
        }

        let renderContent = (this.state.isGoods ?
                <View>
                    {/**headers Image*/}

                    {headresImage}

                    {/**title--suite*/}
                    {this.state.suiteGoodsData.length > 0 ? this.labelTitleRender(I18n.t('default.highValueSets'), 'suite') : null}
                    {/**ListView horizontal---suite*/}
                    {this.state.suiteGoodsData && <FlatList
                        keyExtractor={(item, index) => index}
                        data={this.state.suiteGoodsData}
                        renderItem={(item) => this._renderTopRow(item.item, item.index)}
                        horizontal={true}
                        showsHorizontalScrollIndicator={false}/>}

                    {/**title--global*/}
                    {this.state.globalGoodsData.length > 0 ? this.labelTitleRender(I18n.t('default.shopGlobally'), 'global') : null}
                    {/**ListView horizontal---global*/}
                    {this.state.globalGoodsData.length > 0 && <FlatList
                        keyExtractor={(item, index) => index}
                        data={this.state.globalGoodsData}
                        renderItem={(item) => this._renderTopRow(item.item, item.index, true)}
                        horizontal={true}
                        showsHorizontalScrollIndicator={false}/>
                    }

                    {/**title---promote*/}
                    {this.state.promoteGoodsData.length > 0 ? this.labelTitleRender(I18n.t('default.promotions'), 'promote') : null}
                    {this.state.promoteGoodsData.length > 0 && this.getListView(this.state.promoteGoodsData)}

                    {/**title---new*/}
                    {this.state.newGoodsData.length > 0 ? this.labelTitleRender(I18n.t('default.newProducts'), 'new') : null}
                    {this.state.newGoodsData.length > 0 && this.getListView(this.state.newGoodsData)}


                    {this.state.mid_adver.length > 0 && <AdvertisementView
                        onPress={(item) => this.commonUtils.onClickAdvers(item, this, this.countryIso)}
                        data={this.state.mid_adver}/>}

                    {/**title---hot*/}
                    {this.state.hotGoodsData.length > 0 ? this.labelTitleRender(I18n.t('default.bestSellers'), 'hot') : null}
                    {this.state.hotGoodsData.length > 0 && this.getListView(this.state.hotGoodsData)}

                    {this.state.bottomAdver.map((item, index) => {
                        return <TouchableOpacity
                            key={index}
                            style={[styles.centerImage, StyleUtils.center]}
                            onPress={() => this.commonUtils.onClickAdvers(item, this, this.countryIso)}
                        >
                            <IparImageView
                                errorImage={require('../res/images/ic_image_fail.png')}
                                style={StyleUtils.marginTop}
                                width={'100%'}
                                height={200}
                                url={item.adver_img}/>

                        </TouchableOpacity>
                    })}

                    <FlatList
                        extraData={this.state}
                        data={this.state.goodsData}
                        keyExtractor={(item, index) => index}
                        renderItem={(item) => this.renderHomeListItem(item.item, item.index)}
                    />

                </View> : null
        );

        return (<View style={{flex: 1}}>
                <ScrollView
                    onScroll={(e) => this._contentViewScroll(e)}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={() => this.onLOadData(this.countryIso)}
                        />
                    }
                >
                    {renderContent}

                </ScrollView>
                {this.state.isRefreshingUp &&
                <ActivityIndicator
                    style={{bottom: 16, width: '100%', position: "absolute"}}
                    color={'black'}
                    size={'small'}/>
                }
                {userInfo && userInfo.user_id !== userInfo.main_user_id &&
                <View style={{position: 'absolute', left: 0, right: 0}}>
                    {ViewUtils.renderOperationView(operationViewUserData, operationViewUserData ? this : false, operationViewUserData ? null :
                        () => {
                            if (operationViewType === 0) {
                                this.props.navigator.push({component: VerifyPersonalPage});
                            } else {
                                this.props.navigator.push({
                                    component: BusinessPlanPage,
                                    name: 'BusinessPlanPage',
                                });
                            }
                        }, operationViewTitle, operationViewMsj, this.state.showOperationView, true, () => {
                        this.setState({
                            showOperationView: false,
                        })
                    })}
                </View>}
            </View>
        );

    }

    /**
     * 上传滑动到底部事件
     * */
    _contentViewScroll(e) {
        if (!this.state.refreshingUp) {
            return;
        }
        let offsetY = e.nativeEvent.contentOffset.y; //滑动距离
        let contentSizeHeight = e.nativeEvent.contentSize.height; //scrollView contentSize高度
        let oriageScrollHeight = e.nativeEvent.layoutMeasurement.height; //scrollView高度
        if (offsetY + oriageScrollHeight >= contentSizeHeight - 10) {
            this.getHomeNewData();
        }
    }

    /**
     * 主list item
     */
    renderHomeListItem(rowData, index) {
        if (!rowData) return null;
        if (!rowData.goods) return null;
        var moreType = rowData.type;
        let title = moreType;//
        let isCate = false;//
        if (moreType) {
            switch (moreType) {
                case 'promote':
                    title = I18n.t('default.promotions');
                    break;
                case 'new':
                    title = I18n.t('default.newProducts');
                    break;
                case 'hot':
                    title = I18n.t('default.bestSellers');
                    break;
            }
        } else {
            isCate = true;
            moreType = rowData.cate_id;
            title = rowData.name;
            switch (I18n.locale) {
                case 'en':
                    title = rowData.name_en;
                    break;
                case 'uy':
                    title = rowData.name_uy;
                    break;
                case 'ru':
                    title = rowData.name_ru;
                    break
            }
        }

        return <View>
            {this.labelTitleRender(title, moreType, isCate)}
            {this.getListView(rowData.goods)}
        </View>
    }


    /**
     * horizontal ListView
     * @param rowData
     * @param sectionID
     * @param rowID
     * @returns {*}
     * @private
     */
    _renderTopRow(rowData, i, countryImage) {
        return (
            <GoodsRender
                key={i}
                countryImage={countryImage}
                navigator={this.props.navigator}
                dataSource={rowData}
                goodsBoxSize={3}
            />
        );
    }

    _renderRow(rowData, rowID) {
        return (
            <GoodsRender
                key={rowID}
                navigator={this.props.navigator}
                dataSource={rowData}
            />
        );
    }

    componentWillReceiveProps(nexProps) {

        if (this.state.lang !== I18n.locale) {
            this.setState({
                lang: I18n.locale,
            });
            this.onLOadData(this.countryIso);
        } else if (this.props.userInfo !== nexProps.userInfo) {
            this.onLOadData(this.countryIso);
        }

    }

}

const styles = StyleSheet.create({
    headerImages: {
        width: '100%',
        height: '100%',
    },

    centerImage: {
        width: '100%',
        height: 200,
    },

    gridListStyle: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        // alignItems:'center',
        // justifyContent:'center',
    },

    minContent: {
        textAlign: 'center',
        backgroundColor: 'transparent',
        marginTop: 8,
        padding: 15,
        paddingBottom: 0
    },

    text: {
        fontSize: 14,
        padding: 0,
        flex: 1,
        marginRight: 8,
        textAlign: 'left'
    },

    moreText: {
        fontSize: 18,
        textAlign: 'center',
        color: '#898b8d',
    },
    listView: {
        // marginRight: 16
    },

    moreIcon: {
        width: 18,
        height: 18,
        tintColor: '#898b8d',
    }


});


